<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="处方名字" prop="preName">
        <el-input
          v-model="queryParams.preName"
          placeholder="请输入处方名字"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['medicine:prescription:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['medicine:prescription:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['medicine:prescription:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['medicine:prescription:export']"
        >导出
        </el-button>
      </el-col>
    </el-row>

    <el-table @row-click="handleUpdate" v-loading="loading" :data="prescriptionList"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="处方名字" align="center" prop="preName"/>
      <el-table-column label="价格" align="center" prop="prePrice"/>
      <el-table-column label="创建时间" align="center" prop="gmtCreate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.gmtCreate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="gmtModified" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.gmtModified, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120px">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['medicine:prescription:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['medicine:prescription:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :layout="'total,prev,pager,next,sizes'"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改处方管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="50px">
        <el-form-item label="名字" prop="preName">
          <el-input v-model="form.preName" placeholder="请输入处方名字"/>
        </el-form-item>

        <el-form-item label="药品">
          <span class="input-group" v-for="(item,index) in medicineInfoInputList">
            <el-select @change="medicineChange" filterable v-model="item.medId" style="width: 35%">
              <el-option
                v-for="item in medicineList"
                :key="item.medId"
                :label="item.medName"
                :value="item.medId">
                <span style="float: left">{{ item.medName }}</span>
                <span
                  style="float: right; color: #8492a6; font-size: 12px;margin-left: 10px">{{ item.marketPrice }}元/克</span>
              </el-option>
            </el-select>
            <el-input @input="getTotalPrice(index)" v-model="item.medGram" placeholder="克数"
                      style="width: 40%;margin-left: 10px">
              <template slot="append">克</template>
            </el-input>
            <span @click="addInputGroup" class=" add-icon"><i class="el-icon-circle-plus-outline"/></span>
            <span v-show="medicineInfoInputList.length>1" @click="removeInputGroup(item,index)" class="remove-icon"><i
              class="el-icon-remove-outline"/></span>
          </span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
      <span class="price">
       <span>总价: </span>
        <count-to :start-val="oldPrice" :end-val="totalPrice" prefix="¥" :decimals="2" :duration="1000"
                  class="text-danger"/>
      </span>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listPrescription,
    getPrescription,
    delPrescription,
    addPrescription,
    updatePrescription,
    exportPrescription
  } from '@/api/medicine/prescription'
  import { listMedicine } from '../../../api/medicine/medicine'
  import { computePrice } from '../../../api/medicine/prescription'
  import CountTo from 'vue-count-to'

  export default {
    components: { CountTo },
    name: 'Prescription',
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 处方管理表格数据
        prescriptionList: [],
        // 弹出层标题
        title: '',
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          preName: undefined
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {},
        medicineList: [],
        medicineInfoInputList: [
          {
            medId: '',
            medGram: ''
          }
        ],
        //用来判断是否已选中
        selectList: [],

        oldPrice: 0,
        totalPrice: 0
      }
    },
    created() {
      this.getList()
    },
    watch: {},
    methods: {
      /** 查询处方管理列表 */
      getList() {
        this.loading = true
        listPrescription(this.queryParams).then(response => {
          this.prescriptionList = response.rows
          this.total = response.total
          this.loading = false
        })
      },
      // 取消按钮
      cancel() {
        this.open = false
        this.reset()
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          preId: undefined,
          preName: undefined,
          prePrice: undefined,
          gmtCreate: undefined,
          gmtModified: undefined,
          isEnabled: undefined,
          isDeleted: undefined
        }
        this.resetForm('form')
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1
        this.getList()
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm('queryForm')
        this.handleQuery()
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length != 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset()
        this.getMedicineList()
        this.open = true
        this.title = '添加处方'
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset()
        this.getMedicineList()
        const preId = row.preId || this.ids
        getPrescription(preId).then(response => {
          this.form = response.data
          const medicineList = response.data.medicineList
          if (medicineList.length > 0) {
            this.medicineInfoInputList = medicineList
          }
          this.totalPrice = response.data.prePrice
          this.open = true
          this.title = '修改处方'
        })
      },
      /** 提交按钮 */
      submitForm: function() {
        this.$refs['form'].validate(valid => {
          if (valid) {
            if (this.form.id != undefined) {
              let data = this.form
              data.medicineList = this.medicineInfoInputList
              updatePrescription(data).then(response => {
                if (response.code === 200) {
                  this.msgSuccess('修改成功')
                  this.open = false
                  this.getList()
                }
              })
            } else {

              let data = this.form
              data.medicineList = this.medicineInfoInputList
              addPrescription(data).then(response => {
                if (response.code === 200) {
                  this.msgSuccess('新增成功')
                  this.open = false
                  this.getList()
                }
              })
            }
          }
        })
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids
        this.$confirm('是否确认删除处方管理编号为"' + ids + '"的数据项?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function() {
          return delPrescription(ids)
        }).then(() => {
          this.getList()
          this.msgSuccess('删除成功')
        }).catch(function() {
        })
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams
        this.$confirm('是否确认导出所有处方管理数据项?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function() {
          return exportPrescription(queryParams)
        }).then(response => {
          this.download(response.msg)
        }).catch(function() {
        })
      },

      async getMedicineList() {
        this.medicineList = (await listMedicine()).rows
      },

      medicineChange(value) {

        this.getTotalPrice()

        // const list = this.selectList
        // const isExist = list.some(item => {
        //   if (item.medId === value) {
        //     this.msgInfo('不能重复添加该药品')
        //     return true
        //   }
        // })
        // if (!isExist) {
        //   this.selectList = this.medicineInfoInputList
        //   this.getTotalPrice()
        // } else {
        //   //TODO 判断是否存在
        //   this.medicineInfoInputList = list
        // }

      },

      addInputGroup() {
        this.medicineInfoInputList.push({ medId: '', medGram: '' })
      },
      removeInputGroup(item, index) {
        const medId = this.medicineInfoInputList[index].medId
        let medName = ''
        if (medId !== '') {
          this.medicineList.some(item => {
            if (item.medId === medId) {
              medName = ` [ ${item.medName} ] `
              return true
            }
          })
        }
        this.$confirm(`确定删除${medName}吗`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const list = this.medicineInfoInputList
          list.splice(index, 1)
          this.getTotalPrice()
        })
      },

      async getTotalPrice() {
        this.oldPrice = Number(this.totalPrice)
        //todo 获取金额
        const medicineList = this.medicineInfoInputList.filter(item => {
          //未选择药品,未输入克数,输入不是数字的,不参与计算
          // && !item.medGram.endsWith(".") 表示以'.'结尾的不参与计算
          return item.medGram !== '' && !isNaN(Number(item.medGram)) && item.medId !== ''
        })
        if (medicineList.length > 0) {
          const data = { medicineList }
          const res = await computePrice(data)
          this.totalPrice = Number(res.data)
        } else {
          this.totalPrice = 0
        }
      }

    }
  }
</script>
<style>

  .add-icon {
    font-size: 30px;
    margin-left: 10px;
    color: #409EFF;
  }

  .remove-icon {
    font-size: 30px;
    margin-left: 10px;
    color: #ed5565;
  }

  .el-form-item__content {
    display: flex;
    flex-wrap: wrap;
  }

  .input-group {
    display: flex;
    flex-wrap: wrap;
  }

  @media only screen and (max-width: 767px) {

    .add-icon, .remove-icon {
      font-size: 20px;
      margin-left: 8px;
      color: #409EFF;
    }

    .remove-icon {
      color: #ed5565;
    }


    .input-group {
      display: flex;
      flex-wrap: wrap;
      align-items: baseline;
    }

    .el-select-dropdown__item {
      display: flex;
      justify-content: space-between;
      align-items: baseline;
    }

    .price {
      position: absolute;
      left: 25px;
      bottom: 25px;
    }
  }

</style>
